import json
import os
import shutil
import time
import traceback
import uuid
import requests
from selenium.webdriver import Keys
from pageMethod.launchWebdriver import launchBrowser
from public.Base import PageMethod
from public.config import log, notifyIp
from public.httpBase import httpGet

MAX_RETRIES = 3  # 设置最大重试次数
def PostNotes( mobile, ykId, cookies, title, content, tags, images, tid):
    retries = 0
    while retries < MAX_RETRIES:
        driver = launchBrowser(mobile, tid)
        for cookie in cookies:
            driver.add_cookie(cookie)
        user = PageMethod(driver)
        user.Get("https://creator.xiaohongshu.com/publish/publish?source=")
        try:
            log.info("点击发布笔记", tid)
            user.jsclick("xpath", "//*[@id='content-area']/main/div[1]/div/div[1]/a", tid)

            # 点击上传图文tab
            user.jsclick("xpath", '//span[text()="上传图文"]', tid)
            WebElement_file = user.find_element("class", "upload-input", tid)
            log.info("开始上传图片", tid)
            imagesPathId = str(uuid.uuid4())
            root_path = os.path.dirname(__file__)
            imagesPath = os.path.join(root_path, '..', 'images', f"{imagesPathId}")
            os.makedirs(imagesPath, exist_ok=True)
            for image_url in images:
                response = requests.get(image_url)
                if response.status_code == 200:
                    # 保存图片到本地
                    imageId = str(uuid.uuid4())
                    content_type = response.headers['Content-Type']
                    if content_type == 'image/jpeg':
                        extension = '.jpg'
                    elif content_type == 'image/png':
                        extension = '.png'
                    # 依此类推，对于其他支持的图片格式
                    else:
                        extension = '.jpg'
                    with open(f'{imagesPath}/{imageId}{extension}', 'wb') as f:
                        f.write(response.content)
                    image_path = os.path.abspath(f'{imagesPath}/{imageId}{extension}')
                    WebElement_file.send_keys(image_path)
            if title:
                if len(title) > 20:
                    title = title[:20]
            user.jsText("class", "c-input_inner", title, "arguments[0].value = arguments[1];", tid)
            user.jsText("class", "post-content", content, "arguments[0].innerHTML = arguments[1].replace(/\\n/g, '<br>');",tid)
            # 室内设计[话题]
            if tags:
                for t in tags:
                    user.type("class", "post-content", t, tid)
                    time.sleep(6)
                    user.type("class", "post-content", Keys.ENTER, tid)
            log.info("发布", tid)
            user.jsclick("class", "publishBtn", tid)
            alert = user.find_element("css", "div.alert-title", tid)
            if alert:
                text = user.get_text(alert, tid)
                if text == "图片上传中，请稍后":
                    log.info(text, tid)
                    log.info("提示图片上传中,等待30s再次发布", tid)
                    time.sleep(30)
                    user.jsclick("class", "publishBtn", tid)
                    alert = user.find_element("css", "div.alert-title", tid)

            if alert:
                text = user.get_text(alert, tid)
                log.info(text, tid)
                retries += 1
                if retries == MAX_RETRIES:
                    notify(ykId, "", -1, "", text, tid)
                user.quit_browser(tid)
                shutil.rmtree(imagesPath)
                continue
            else:
                element = user.element_wait("css", "p.title", tid)
                if element:
                    statsData = noteStats(cookies, mobile, tid)
                    statsData = json.loads(statsData)
                    note_info = statsData.get("data").get("note_infos")[0]
                    if note_info.get("title") == title:
                        xhsId = note_info.get("id")
                        post_time = note_info.get("post_time")
                        status = 1
                        notify(ykId, xhsId, status, post_time, "发布成功", tid)
                        shutil.rmtree(imagesPath)
                        user.quit_browser(tid)
                        return
                    else:
                        log.info("出现发布成功元素但是接口返回没有新发布笔记", tid)
                        user.quit_browser(tid)
                        return
                else:
                    retries += 1
                    user.quit_browser(tid)
                    continue
        except:
            msg = traceback.format_exc()
            log.info(f"Attempt {retries + 1} failed with :{msg}", tid)
            retries += 1
            user.quit_browser(tid)
            time.sleep(5)


    log.error("重试三次都失败", tid)

def noteStats(driver_cookies, mobile, tid):
    url = "https://creator.xiaohongshu.com/api/galaxy/creator/data/note_stats/new?page=1&page_size=1000&note_type=0&is_recent=false"

    session_cookies = requests.cookies.RequestsCookieJar()

    # 将 WebDriver 中获取的 cookies 添加到 requests 的 cookie jar
    for cookie in driver_cookies:
        session_cookies.set(cookie['name'], cookie['value'], domain=cookie.get('domain', ''),
                            path=cookie.get('path', '/'))
    text = httpGet(url, 'https://creator.xiaohongshu.com/creator/notes', session_cookies, mobile, tid)

    # response = requests.request("GET", url, headers=headers, data=payload, cookies=session_cookies, proxies=proxies)
    log.info(f"noteStats返回{text}", tid)
    return text

def notify(ykId,xhsId,status,post_time,msg, tid):
    url = f"{notifyIp}/api/ai/xiaoHongShu/notify"

    payload = json.dumps({
        "ykId": ykId,
        "xhsId": xhsId,
        "status": status,
        "postTime": post_time,
        "msg": msg
    })
    headers = {
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)

    log.info(f"回调返回{response.text}", tid)
    return response.text


